import calendar
import datetime
import pytz

from django.conf import settings
from django.utils import timezone


def start_of_month_in_milli():
    today = timezone.now().replace(day=1, hour=0, minute=0, second=0)
    return today.timestamp() * 1e3


def end_of_month_in_milli():
    today = timezone.now()
    weekday, days = calendar.monthrange(today.year, today.month)
    today = today.replace(day=days, hour=23, minute=59, second=59)
    return today.timestamp() * 1e3


def ts_in_milli_to_dt(ts_in_milli):
    dt = datetime.datetime.fromtimestamp(ts_in_milli / 1e3)
    return dt.replace(tzinfo=timezone.now().tzinfo)


def utc_ts_in_milli_to_dt(ts_in_milli):
    dt = datetime.datetime.utcfromtimestamp(ts_in_milli / 1e3)
    return dt


def get_dt(year, month, day):
    today = timezone.make_aware(datetime.datetime.now(),
                                timezone.get_default_timezone())
    year = int(year)
    month = int(month)
    day = int(day)
    return today.replace(year=year, month=month, day=day)


def zone_conflict(zone_conflict_items):
    zones = {}
    for item in zone_conflict_items:
        day = ts_in_milli_to_dt(item['start']).day
        if day not in zones:
            zones[day] = []
        zones[day].append(item)
    # print('zones', zones)

    zone_conflict_list = []

    for day, day_zones in zones.items():
        day_zones_len = len(day_zones)
        is_conflict = False
        for i in range(day_zones_len):
            for j in range(day_zones_len):
                # condition = -1
                if i == j:
                    continue
                if day_zones[i]['end'] >= day_zones[j]['start'] and \
                        day_zones[i]['start'] <= day_zones[j]['start']:
                    is_conflict = True
                    # condition = 1
                if day_zones[i]['start'] >= day_zones[j]['start'] and \
                        day_zones[i]['end'] <= day_zones[j]['end']:
                    is_conflict = True
                    # condition = 2
                if day_zones[j]['start'] >= day_zones[i]['start'] and \
                        day_zones[j]['end'] <= day_zones[i]['end']:
                    is_conflict = True
                    # condition = 3
                if day_zones[i]['start'] <= day_zones[j]['end'] and \
                        day_zones[i]['end'] >= day_zones[j]['end']:
                    is_conflict = True
                    # condition = 4
                if (is_conflict and
                        day_zones[i]['zone'] == day_zones[j]['zone']):
                    zone_conflict_list.append(day)
                    break
                else:
                    is_conflict = False
            if is_conflict:
                break
    # print('zone_conflict_list', zone_conflict_list)
    zone_conflict_list.sort()
    return zone_conflict_list


def sort_by_something_for_users(request, queryset, sort_f, sort_f_value):
    sort_dict = {}
    sort_dict['username'] = request.GET.get('username')
    sort_dict['first_name'] = request.GET.get('first_name')
    sort_dict['last_name'] = request.GET.get('last_name')
    sort_dict['email'] = request.GET.get('email')
    for parm, parm_value in sort_dict.items():
        if parm_value == 'asc':
            queryset = queryset.order_by("user__" + parm)
            sort_f = parm
            sort_f_value = "asc"
            break
        if parm_value == 'dsc':
            queryset = queryset.order_by("-" + "user__" + parm)
            sort_f = parm
            sort_f_value = "dsc"
            break
    return queryset, sort_f, sort_f_value


def str_to_dt(str_time):
    """convert str to datetime obj

    Args:
        str_time (str): 时间字符串，如：2017-7-14 12:00:00

    Returns:
        datetime: 供数据库使用的 datetime obj，加入时区信息
    """
    time = datetime.datetime.strptime(str_time,
                                      "%Y-%m-%d %H:%M:%S")
    tz = pytz.timezone(settings.TIME_ZONE)
    return tz.localize(time)
